<?php

namespace App\Tools;

class Signature
{
    protected const SIGN_KEY = 'sign';

    /**
     * 验证签名.
     *
     * @param $data
     * @param $sign
     */
    public static function verify($data, $sign, $secret = ''): bool
    {
        return self::generate($data, $secret) === $sign;
    }

    /**
     * 生成签名.
     *
     * @return false|string
     */
    public static function generate(array $data, $secret = ''): string
    {
        ksort($data);

        return hash_hmac('sha256', http_build_query($data, '', '&', PHP_QUERY_RFC3986), $secret);
    }

    /**
     * 对数组进行签名并返回签名后的数据.
     */
    public static function signData(array $data, $secret = ''): array
    {
        $data[self::SIGN_KEY] = self::generate($data, $secret);

        return $data;
    }
}
